package de.baumann.browser;

import android.app.Application;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Process;
import android.support.multidex.MultiDex;
import android.util.Log;

import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.FormatStrategy;
import com.orhanobut.logger.Logger;
import com.orhanobut.logger.PrettyFormatStrategy;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UploadManager;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.File;
import java.security.Provider;
import java.security.Security;

import de.baumann.browser.db.DaoMaster;
import de.baumann.browser.db.DaoSession;
import de.baumann.browser.utils.CrashHandler;
import de.baumann.browser.utils.SPUtilKt;
import de.baumann.browser.utils.UnicornUtil;

import static de.baumann.browser.utils.StringUtil.getProcessName;

/**
 * @author
 */
public class OdinApplication extends Application {
    private static OdinApplication instance;
    private static UploadManager uploadManager;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        if (inMainProcess()) {
            SPUtilKt.init(this);
            initGreenDao();
            initLogger();
            initQiNiu();
            initUmeng();
            initQiYu();
            if (!BuildConfig.DEBUG) {
                CrashHandler.getInstance().init(getInstance());
            }
            initWebView();
            setupBouncyCastle();
        }
    }

    private void initQiYu() {
        UnicornUtil.Companion.init(this);
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(base);
    }

    private void initQiNiu() {
        Configuration config = new Configuration.Builder()
                // 分片上传时，每片的大小。 默认256K
                .chunkSize(512 * 1024)
                // 启用分片上传阀值。默认512K
                .putThreshhold(1024 * 1024)
                // 链接超时。默认10秒
                .connectTimeout(10)
                // 是否使用https上传域名
                .useHttps(true)
                // 服务器响应超时。默认60秒
                .responseTimeout(60)
                .build();
        uploadManager = new UploadManager(config);
    }

    private void initUmeng() {
        if (BuildConfig.DEBUG) {
            UMConfigure.setLogEnabled(true);
        }
        MobclickAgent.setSessionContinueMillis(1000 * 60);
        UMConfigure.init(this, ConstantKt.UMENG_APP_KEY, "", UMConfigure.DEVICE_TYPE_PHONE, "");

        PlatformConfig.setWeixin(ConstantKt.WX_APP_ID, ConstantKt.WX_APP_KEY);
        PlatformConfig.setQQZone(ConstantKt.QQ_ZONE_ID, ConstantKt.QQ_ZONE_KEY);

        MobclickAgent.setSessionContinueMillis(1000 * 40);
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
    }

    private void initLogger() {
        FormatStrategy formatStrategy = PrettyFormatStrategy.newBuilder()
                .showThreadInfo(false)
                .methodCount(3)
                .methodOffset(7)
                .tag("ODIN")
                .build();
        Logger.addLogAdapter(new AndroidLogAdapter(formatStrategy) {
            @Override
            public boolean isLoggable(int priority, String tag) {
                return BuildConfig.DEBUG;
            }
        });
    }

    public static OdinApplication getInstance() {
        return instance;
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    private boolean inMainProcess() {
        String packageName = getPackageName();
        String processName = getProcessName(Process.myPid());
        return packageName.equals(processName);
    }

    public static UploadManager getUploadManager() {
        return uploadManager;
    }

    private void initWebView() {
        QbSdk.initX5Environment(getApplicationContext(), new QbSdk.PreInitCallback() {
            @Override
            public void onCoreInitFinished() {
                Log.d("1111", "onCoreInitFinished: ");
            }

            @Override
            public void onViewInitFinished(boolean b) {
                Log.d("1111", "onViewInitFinished: " + b);
            }
        });
    }

    private void setupBouncyCastle() {
        final Provider provider = Security.getProvider(BouncyCastleProvider.PROVIDER_NAME);
        if (provider == null) {
            // Web3j will set up the provider lazily when it's first used.
            return;
        }
        if (provider.getClass().equals(BouncyCastleProvider.class)) {
            // BC with same package name, shouldn't happen in real life.
            return;
        }
        // Android registers its own BC provider. As it might be outdated and might not include
        // all needed ciphers, we substitute it with a known BC bundled in the app.
        // Android's BC has its package rewritten to "com.android.org.bouncycastle" and because
        // of that it's possible to have another BC implementation loaded in VM.
        Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME);
        Security.insertProviderAt(new BouncyCastleProvider(), 1);
    }

    public static File getDir() {
        return instance.getDir("ODIN", Context.MODE_PRIVATE);
    }
    private DaoSession daoSession;
    private void initGreenDao() {
        //创建数据库表
        DaoMaster.DevOpenHelper mHelper = new DaoMaster.DevOpenHelper(this, "wallet", null);
        SQLiteDatabase db = mHelper.getWritableDatabase();
        daoSession = new DaoMaster(db).newSession();
    }

    public DaoSession getDaoSession() {
        return daoSession;
    }
}
